﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using RN.ERP.Web.ModelService;
using Newtonsoft.Json;
using Fly.Common.Linq;
using Fly.Common.WorkFlow;
using Telerik.Web.UI;
using Telerik.Web.UI.Skins;
using System.Configuration;

namespace RN.ERP.Web
{
    public partial class ManagerMain : BasePage//System.Web.UI.Page
    {
        protected string AreaCode
        {
            get
            {
                return UserInfo.CurrentArea;
            }
        }
        protected string CorpUserGuid
        {
            get
            {
                return UserInfo.CorpUserGuid;
            }
        }
        protected string RoleId
        {
            get
            {
                return UserInfo.RoleId;
            }
        }
#if DEBUG
        public override bool IsCheckPermission
        {
            get { return false; }
        }
#endif
       
        private EnterpriseService.EnterpriseServiceClient enterpriseServiceClient = new EnterpriseService.EnterpriseServiceClient();
        private BasicService.BasicServiceClient basicServiceClient = new BasicService.BasicServiceClient();
        protected void Page_Load(object sender, EventArgs e)
        {
            BindData();
        }

        protected void rdgLocalCorps_NeedDataSource(object source, GridNeedDataSourceEventArgs e)
        {
            var tabName = hdnSelectTagName.Value;
            if (tabName == "tagContent0")
            {
                List<string> listFlow = GetFlowCodes();
                List<QueryCompanyInfoCondition> queryCompanyInfoList = new List<QueryCompanyInfoCondition>();
                var classIds = GetSysClassId();
                foreach (var f in listFlow)
                {
                    if (classIds.Count > 0)
                    {
                        foreach (var clsIsd in classIds)
                        {
                            QueryCompanyInfoCondition queryCompanyInfoCondition = new QueryCompanyInfoCondition();
                            queryCompanyInfoCondition.AreaCode = new ParameterValue<string>() { O = OptEnum.StartWith, V = UserInfo.AreaCode };
                            queryCompanyInfoCondition.FlowCode = new ParameterValue<string>() { O = OptEnum.Equal, V = f };
                            queryCompanyInfoCondition.classID = new ParameterValue<int?>() { O = OptEnum.Equal, V = clsIsd };
                            queryCompanyInfoList.Add(queryCompanyInfoCondition);
                        }

                    }
                    else
                    {
                        QueryCompanyInfoCondition queryCompanyInfoCondition = new QueryCompanyInfoCondition();
                        queryCompanyInfoCondition.AreaCode = new ParameterValue<string>() { O = OptEnum.StartWith, V = UserInfo.AreaCode };
                        queryCompanyInfoCondition.FlowCode = new ParameterValue<string>() { O = OptEnum.Equal, V = f };

                        queryCompanyInfoList.Add(queryCompanyInfoCondition);
                    }
                }

                var corp = enterpriseServiceClient.GetCompanyAllInfo(JsonConvert.SerializeObject(queryCompanyInfoList), rdgLocalCorps.PageSize, rdgLocalCorps.CurrentPageIndex + 1, UserInfo.CurrentArea);
                var corpInfo = JsonConvert.DeserializeObject<IList<CompanyInfo>>(corp);
                int cnt = enterpriseServiceClient.GetCompanyCount(JsonConvert.SerializeObject(queryCompanyInfoList), UserInfo.CurrentArea);
                rdgLocalCorps.AllowCustomPaging = true;
                rdgLocalCorps.VirtualItemCount = cnt;
                rdgLocalCorps.DataSource = corpInfo;
            }
        }

        protected void rglEmbranchMents_NeedDataSource(object source, GridNeedDataSourceEventArgs e)
        {
            var tabName = hdnSelectTagName.Value;
            if (tabName == "tagContent1")
            {
                List<string> listFlow = GetFlowCodes();
                List<QueryCompanyInfoCondition> queryCompanyInfoList = new List<QueryCompanyInfoCondition>();
                var classIds = GetSysClassId();
                foreach (var f in listFlow)
                {
                    if (classIds.Count > 0)
                    {
                        foreach (var clsIsd in classIds)
                        {
                            QueryCompanyInfoCondition queryCompanyInfoCondition = new QueryCompanyInfoCondition();
                            queryCompanyInfoCondition.AreaCode = new ParameterValue<string>() { O = OptEnum.NotStartWith, V = UserInfo.AreaCode };
                            queryCompanyInfoCondition.FlowCode = new ParameterValue<string>() { O = OptEnum.Equal, V = f };
                            queryCompanyInfoCondition.classID = new ParameterValue<int?>() { O = OptEnum.Equal, V = clsIsd };
                            queryCompanyInfoList.Add(queryCompanyInfoCondition);
                        }

                    }
                    else
                    {
                        QueryCompanyInfoCondition queryCompanyInfoCondition = new QueryCompanyInfoCondition();
                        queryCompanyInfoCondition.AreaCode = new ParameterValue<string>() { O = OptEnum.NotStartWith, V = UserInfo.AreaCode };
                        queryCompanyInfoCondition.FlowCode = new ParameterValue<string>() { O = OptEnum.Equal, V = f };
                        queryCompanyInfoList.Add(queryCompanyInfoCondition);
                    }
                }
                var corp = enterpriseServiceClient.GetCompanyAllInfo(JsonConvert.SerializeObject(queryCompanyInfoList), rglEmbranchMents.PageSize, rglEmbranchMents.CurrentPageIndex + 1, UserInfo.CurrentArea);
                var corpInfo = JsonConvert.DeserializeObject<IList<CompanyInfo>>(corp);
                int cnt = enterpriseServiceClient.GetCompanyCount(JsonConvert.SerializeObject(queryCompanyInfoList), UserInfo.CurrentArea);
                rglEmbranchMents.AllowCustomPaging = true;
                rglEmbranchMents.VirtualItemCount = cnt;
                rglEmbranchMents.DataSource = corpInfo;
            }
        }
        /// <summary>
        /// 未实现
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void RadToolBar1_ButtonClick(object sender, RadToolBarEventArgs e)
        {
            if (e.Item.Text == "查看")
            {
                try
                {
                    int checkCount = 0;
                    int pid = -1;
                    foreach (GridDataItem dataItem in rdgLocalCorps.MasterTableView.Items)
                    {
                        if ((dataItem.FindControl("CheckBox1") as CheckBox).Checked == true)
                        {
                            var id = dataItem.GetDataKeyValue("ID");
                            checkCount++;
                            pid = int.Parse(id.ToString());
                            if (checkCount >= 2)
                            {
                                //只能选择一条数据
                                ScriptManager.RegisterStartupScript(this, this.GetType(), "", "alert('只能选择一条数据！');", true);
                                return;
                            }
                        }
                    }
                    if (checkCount == 0)
                    {
                        ScriptManager.RegisterStartupScript(this, this.GetType(), "", "alert('请选择要查看的数据！');", true);
                    }
                    else if (checkCount == 1)
                    {
                        Response.Redirect("#");
                    }
                }
                catch (Exception ex)
                {
                    ScriptManager.RegisterStartupScript(this, this.GetType(), "", "alert('数据加载失败！');", true);
                }
            }

        }

        private void BindData()
        {
            ltrLoginUser.Text = UserInfo.UserName;
            ltrUserName.Text = UserInfo.UserName;
            //ltrUserType.Text = UserInfo.RoleType;
            //ltrUserArea.Text = basicServiceClient.GetAddress(UserInfo.AreaCode);
        }

        /// <summary>
        /// 客户端grid刷新
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void RadAjaxManager1_AjaxRequest(object sender, AjaxRequestEventArgs e)
        {
            if (e.Argument == "LocalCorp")
            {
                rdgLocalCorps.MasterTableView.SortExpressions.Clear();
                rdgLocalCorps.MasterTableView.GroupByExpressions.Clear();
                rdgLocalCorps.Rebind();
            }
            if (e.Argument == "EmbranchCorp")
            {
                rglEmbranchMents.MasterTableView.SortExpressions.Clear();
                rglEmbranchMents.MasterTableView.GroupByExpressions.Clear();
                rglEmbranchMents.Rebind();
            }
            if (e.Argument == "Person")
            {
                rgPersonList.MasterTableView.SortExpressions.Clear();
                rgPersonList.MasterTableView.GroupByExpressions.Clear();
                rgPersonList.Rebind();
            }
        } 

        protected string GetCorpClassKind(string type)
        {
            string output = string.Empty;
            if (!String.IsNullOrEmpty(type))
            {
              
              try
              {
                  Dictionary<string, string> CorpTypeDic = JsonConvert.DeserializeObject<Dictionary<string, string>>
                  (Application[ApplicationConstant.APPLICATION_CORPUSERTYPE].ToString());
                  output = CorpTypeDic[type];
              }
              catch
              {
                  output = "";
              }
            }
            return output;
        }

        #region 人员审核
        /// <summary>
        /// 取得人员信息参数
        /// </summary>
        /// <returns></returns>
        private string GetQueryConditions()
        {
            ///设置查询参数
            List<QueryPersonInfoCondition> list = new List<QueryPersonInfoCondition>();
            var flowCodes = GetManagerFlowCodes();
            var classIds = GetSysClassId();
            foreach (var flow in flowCodes)
            {
                if (classIds.Count > 0)
                {
                    foreach (var clsId in classIds)
                    {
                        QueryPersonInfoCondition con = new QueryPersonInfoCondition();
                        con.TypeFlag = new ParameterValue<string> { V = "-1", O = OptEnum.Like };
                        con.FlowCode = new ParameterValue<string> { V = flow, O = OptEnum.Equal };
                        con.ClassId = new ParameterValue<int?>() { V = clsId+10, O = OptEnum.Equal };
                        con.AreaCode = new ParameterValue<string>() { V=UserInfo.AreaCode,O=OptEnum.StartWith};
                        list.Add(con);
                    }
                }
                else
                {
                    QueryPersonInfoCondition con = new QueryPersonInfoCondition();
                    con.TypeFlag = new ParameterValue<string> { V = "-1", O = OptEnum.Like };
                    con.FlowCode = new ParameterValue<string> { V = flow, O = OptEnum.Equal };
                    con.AreaCode = new ParameterValue<string>() { V = UserInfo.AreaCode, O = OptEnum.StartWith };
                    list.Add(con);
                }
            }
            return JsonConvert.SerializeObject(list);
        }

        /// <summary>
        /// 取得人员基本信息
        /// </summary>
        /// <param name="empGuid"></param>
        /// <param name="areaCode"></param>
        private List<ModelService.tb_Emp_Manager> GetEmpManagersList(string areaCode, int currentPageIndex, int pageSize)
        {
            try
            {
                using (PersonService.PersonServiceClient client = new PersonService.PersonServiceClient())
                {
                    string queryStr = GetQueryConditions();
                    rgPersonList.VirtualItemCount = client.GetEmpManagerListCount(queryStr, areaCode);
                    string result = client.GetEmpManagersList(currentPageIndex + 1, pageSize, queryStr, areaCode);
                    return JsonConvert.DeserializeObject<List<ModelService.tb_Emp_Manager>>(result);
                }
            }
            catch
            {
                return null;
            }
        }

        /// <summary>
        /// 绑定人员信息
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        public void rgPersonList_NeedDataSource(object sender, GridNeedDataSourceEventArgs e)
        {
            var tabName = hdnSelectTagName.Value;
            if (tabName == "tagContent3")
            {

                string areaCode = AreaCode;
                if (AreaCode.Length > 2)
                {
                    areaCode = AreaCode.Substring(0, 2);
                }
                int currentPageIndex = rgPersonList.CurrentPageIndex;
                int pageSize = rgPersonList.MasterTableView.PageSize;
                var emps = GetEmpManagersList(areaCode, currentPageIndex, pageSize);
                rgPersonList.DataSource = emps;
            }
        }

        #endregion

        private List<int> GetSysClassId()
        {
            var classId = ConfigurationManager.AppSettings["sysClassId"];
            List<int> list = new List<int>();
            if (!string.IsNullOrEmpty(classId))
            {
                foreach (var clsId in classId.Split(','))
                {
                    if (!string.IsNullOrEmpty(clsId))
                    {
                        list.Add(int.Parse(clsId));
                    }
                }
            }
            return list;
        }

        private List<string> GetFlowCodes()
        {
            List<string> listFlow = new List<string>();
            string msg = string.Empty;
            ////默认取施工企业审核流程
            var allStatus = JsonConvert.DeserializeObject<Dictionary<string, string>>(basicServiceClient.GetAllFlowStatus(out msg, UserInfo.CurrentArea, UserInfo.RoleId, "2501"));
            ////角色暂时不处理，等待流程组件的完善
            if (allStatus != null && allStatus.ContainsKey("处理中"))
            {
                var flowCodes = allStatus["处理中"];
                foreach (var f in flowCodes.Split('|'))
                {
                    listFlow.Add(f);
                }
            }
            return listFlow;
        }

        private List<string> GetManagerFlowCodes()
        {
            List<string> listFlow = new List<string>();
            string msg = string.Empty;
            ////默认取施工企业人员审核流程
            var allStatus = JsonConvert.DeserializeObject<Dictionary<string, string>>(basicServiceClient.GetAllFlowStatus(out msg, UserInfo.CurrentArea, UserInfo.RoleId, "2511"));
            ////角色暂时不处理，等待流程组件的完善
            if (allStatus != null && allStatus.ContainsKey("处理中"))
            {
                var flowCodes = allStatus["处理中"];
                foreach (var f in flowCodes.Split('|'))
                {
                    listFlow.Add(f);
                }
            }
            return listFlow;
        }

    }
}